package com.huike.business.service.impl;


import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.TbBusinessTrackRecord;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.business.mapper.TbBusinessTrackRecordMapper;
import com.huike.business.service.ITbBusinessTrackRecordService;
import com.huike.clues.service.ISysDictDataService;
import com.huike.common.utils.DateUtils;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.bean.BeanUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 商机跟进记录Service业务层处理
 */
@Service
public class TbBusinessTrackRecordServiceImpl implements ITbBusinessTrackRecordService {

    @Autowired
    private TbBusinessTrackRecordMapper recordMapper;
    @Autowired
    private TbBusinessMapper businessMapper;
    @Autowired
    private ISysDictDataService sysDictDataService;


    /**
     *新增商机跟进记录
     */
    @Override
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public Object insertTrackRecord(BusinessTrackVo businessTrackVo) {
        //获取用户名
        String username = SecurityUtils.getUsername();
        //获取创建时间
        Date now = new Date();
        businessTrackVo.setCreateBy(username);
        businessTrackVo.setCreateTime(now);
        //创建 tbBusiness对象
        TbBusiness tbBusiness = new TbBusiness();
//        设置忽略字段
        String[] strs =new String[]{"id","status","createBy","createTime","params"};
        //复制对象
        BeanUtils.copyProperties(businessTrackVo, tbBusiness, strs);
        tbBusiness.setId(businessTrackVo.getBusinessId());
        //修改商机表
        businessMapper.updateTbBusiness( tbBusiness);
        // 新增商机跟进记录 到跟进表
        return recordMapper.insertTrackRecord(businessTrackVo);
    }

    /**
     * 查询商机跟进记录列表
     */
    @Override
    public List<TbBusinessTrackRecord> selectBusinessTrackRecords(Long businessId) {
        List<TbBusinessTrackRecord> businessTrackRecords = recordMapper.selectBusinessTrackRecords(businessId);
        for (TbBusinessTrackRecord businessTrackRecord : businessTrackRecords) {
            String keyItems = businessTrackRecord.getKeyItems();
            String[] split = keyItems.split(",");
            for (String s : split) {
                //查询数据字典
                String lable = sysDictDataService.selectDictLabel("communication_point", s);
                List<String> keys = businessTrackRecord.getKeys();
                keys.add(lable);
            }
        }
        return businessTrackRecords;
    }
}
